<template>
  <!-- 产品管理页 -->
  <div class="product">
    产品管理页
    <!-- 头部区域 -->
    <div class="header">
      <!-- 添加按钮 -->
      <el-button type="danger" @click="addProduct">添加</el-button>
      <!-- 产品名称输入框 -->
      <el-input
        placeholder="请输入内容"
        v-model="productName"
        clearable
        style="width: 240px"
      >
      </el-input>
      <!-- 产品状态输入框 -->
      <el-select v-model="productStatus" clearable placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <!-- 栏目选择框 -->
      <el-select v-model="productCategoryId" clearable placeholder="请选择">
        <el-option
          v-for="category in categoryData.filter(
            (item) => item.parentId == null
          )"
          :key="category.id"
          :label="category.name"
          :value="category.id"
        >
        </el-option>
      </el-select>
      <!-- 查询按钮 -->
      <el-button type="danger" @click="seleteProduct">查询</el-button>
    </div>
    <!--图表区域  -->
    <div class="table_content">
      <!-- tabledate 整个表格的数据源 -->
      <el-table :data="productData" style="width: 100%">
        <!-- 序号 -->
        <el-table-column prop="id" label="序号" align="center">
        </el-table-column>
        <!-- 产品编号 -->
        <el-table-column
          prop="productCategoryId"
          label="产品编号"
          align="center"
        >
        </el-table-column>
        <!-- 名称 -->
        <el-table-column prop="name" label="名称" align="center">
        </el-table-column>
        <!-- 图片 -->
        <el-table-column label="图片" align="center">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            >
            </el-image>
          </template>
        </el-table-column>
        <!-- 价格 -->
        <el-table-column prop="price" label="价格" align="center">
        </el-table-column>
        <!-- 状态 -->
        <el-table-column prop="status" label="状态" align="center">
        </el-table-column>
        <!-- 所属栏目 -->
        <el-table-column prop="description" label="所属栏目" align="center">
        </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button @click="editProduct(scope.row)" type="info" size="small"
              >查看</el-button
            >
            <el-button
              size="small"
              v-if="scope.row.status == '正常'"
              type="success"
              @click="clickOffLine(scope.row.id)"
              >下架</el-button
            >
            <el-button
              type="danger"
              size="small"
              v-else
              @click="clickOnLine(scope.row.id)"
              >上架</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部区域 -->
    <div class="paginetion">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 模态框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      @close="dialogClose"
    >
      <!-- 表单区域 -->
      <!-- ：model 表单对象 最终我们要提交的那个表单对象 -->
      <!-- ：rules 表单验证的规则 -->
      <!-- ref 类比与id 最终通过ref 找到这张表单 -->
      <el-form
        :model="productForm"
        :rules="rules"
        ref="product_form"
        label-width="80px"
      >
        <!--  产品名称-->
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <!-- 所属栏目 -->
        <el-form-item label="所属栏目" prop="productCategoryId">
          <el-select
            v-model="productForm.productCategoryId"
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="category in categoryData.filter(
                (item) => item.parentId == null
              )"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!--价格 -->
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="productForm.price"></el-input>
        </el-form-item>
        <!--封面 -->
        <el-form-item label="封面" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL1"
            :show-file-list="false"
            v-model="productForm.photo"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="productForm.photo" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!--产品描述 -->
        <el-form-item label="产品描述" prop="description">
          <el-input
            type="textarea"
            v-model="productForm.description"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { get, post } from "@/utils/request";
import { mapActions, mapState } from "vuex";
//引入文件上传路径 和文件预览的路径
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  data() {
    return {
      // 图片上传的地址
      uploadFileURL1: uploadFileURL,
      //图片显示路径
      imageUrl: "",
      // 当前页码
      page: 1,
      // 每页要展示的数量
      pageSize: 4,
      //查询名称
      productName: "",
      // 查询状态
      productStatus: "",
      // 查询分类编号
      productCategoryId: "",
      // 产品数组
      productData: {},
      //判断是否有查询
      isQuery: false,
      options: [
        {
          value: "正常",
          label: "正常",
        },
        {
          value: "下架",
          label: "下架",
        },
      ],
      // 表格数据
      productData: [],
      // 页面展示的总条数
      total: 10,
      //模态框
      // 模态框显示
      dialogFormVisible: false,
      // 模态框的标题
      dialogTitle: "",
      // 表单对象
      productForm: {
        // 产品名称
        name: "",
        //产品栏目
        productCategoryId: "",
        // 价格
        price: "",
        // 封面
        photo: "",
        // 产品描述
        description: "",
      },
      // 表单验证规则
      rules: {
        // 产品名称
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        //产品栏目
        productCategoryId: [
          { required: true, message: "请选择产品栏目", trigger: "change" },
        ],
        // 价格
        price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { type: "number", message: "价格必须是数字" },
        ],
        // 封面
        photo: [
          {
            required: true,
            message: "请选择图片",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("category", ["categoryData"]),
  },
  methods: {
    //编辑产品
    editProduct(row) {
      // 将当前点击的这一行对象 赋值到 表单对象里
      // 浅拷贝 赋值对象的引用 对象的内存地址 用的还是同一个
      // 深拷贝
      this.productForm = { ...row };
      // 设置模态框的标题
      this.dialogTitle = "编辑产品";
      // 让模态框显示出来
      this.dialogFormVisible = true;
      //
      this.imageUrl = this.productForm.photo;
    },
    //添加产品
    addProduct() {
      // 输入框归空
      this.productForm = {};
      // 设置模态框的标题
      this.dialogTitle = "添加产品";
      // 让模态框显示出来
      this.dialogFormVisible = true;
      // 将图片置空
      this.imageUrl = "";
    },
    //..mapAction("category模块的文件名"，["对应方法"])
    ...mapActions("category", ["getAllCategoryData"]),
    queryCategoryData() {
      let data = {
        page: 1,
        pageSize: 100,
      };
      // 调用在vuex 中定义好的方法。
      this.getAllCategoryData(data);
    },
    //按条件查询
    seleteProduct() {
      let data = {
        page: this.page,
        pageSize: this.pageSize,
      };
      this.isQuery = false;
      if (!this.productName == "") {
        data.name = this.productName;
        this.isQuery = true;
      }
      if (!this.productStatus == "") {
        data.status = this.productStatus;
        this.isQuery = true;
      }
      if (!this.productCategoryId == "") {
        data.productCategoryId = this.productCategoryId;
        this.isQuery = true;
      }
      this.geALLProductData(data);
    },
    // 控制每页条数的
    handleSizeChange(val) {
      // 修改每页获取的数据条数
      this.pageSize = val;
      // 是当前页面回到第一页
      this.page = 1;
      this.seleteProduct();
    },

    // 修改前页显示的页数
    handleCurrentChange(val) {
      //修改当前页面
      this.page = val;
      // 从新获取数据
      this.seleteProduct();
      //console.log(`当前页: ${val}`);
    },
    // 获取页面商品数据
    async geALLProductData(data) {
      let res = await get("/product/pageQuery", data);
      this.total = res.data.total;
      this.productData = res.data.list;
      //console.log(res);
    },
    //修改商品上架
    async clickOnLine(id) {
      // 发送上架请求
      let res = await get("/product/online", { id });
      if (res.status == 200) {
        this.$message({
          message: res.message,
          type: "success",
        });
      }
      //从新刷新数据
      this.seleteProduct();
    },
    //修改商品下架
    async clickOffLine(id) {
      // 发送上架请求
      let res = await get("/product/offline", { id });
      if (res.status == 200) {
        this.$message({
          message: res.message,
          type: "success",
        });
      }
      //从新刷新数据
      this.seleteProduct();
    },
    // 表单提交
    submitForm() {
      this.$refs["product_form"].validate(async (valid) => {
        if (valid) {
          // 发送表单验证的请求，提交表单对象
          let res = await post("/product/saveOrUpdate", this.productForm);
          // 给用户一个成功的提示
          if (res.status == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
          }
          // 刷新页面
          this.seleteProduct();
          //  调用关闭模态框的方法
          this.dialogFormVisible = false;
          console.log(res);
        } else {
          console.log("error submit!!");
        }
      });
    },
    // 关闭模态框 调用表单重置的方法
    dialogClose() {
      this.$refs["product_form"].resetFields();
      setTimeout(() => {
        this.dialogFormVisible = false;
      }, 200);
    },
    // 上传成功后回调的
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // 上传成功之后 更新imgurl预览图片的地址
      this.productForm.photo = showFileURL + res.data.id;
      console.log(this.productForm.photo);
    },
    // 上传之前，要做的一些限制
    beforeAvatarUpload(file) {
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传头像图片大小不能超过 3MB!");
      }
    },
  },
  created() {
    //开始加载数据
    this.geALLProductData({
      page: this.page,
      pageSize: this.pageSize,
    });
    // 自动获取产品栏目的数据
    this.queryCategoryData();
  },
  mounted() {},
};
</script>
<style scoped>
/* 设置头部样式 */
.header {
  line-height: 40px;
}
/* 分页底部样式 */
.paginetion {
  position: fixed;
  right: 30px;
  bottom: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>